package com.itheima.dao;

import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * ClassName:RoleDao
 * Package:com.itheima.dao
 * Description:
 * Date:2020/3/11 22:48
 * User: snow
 */
@Repository
public interface RoleDao {
	//根据用户id查询出所有对应的角色
	@Select("select * from role where id in (select roleId from users_role where userId=#{id})")
	@Results({
			@Result(id = true, property = "id", column = "id"),
			@Result(property = "roleName", column = "role_name"),
			@Result(property = "roleDesc", column = "role_desc"),
			@Result(property = "permissions", column = "id", javaType = java.util.List.class,
					many = @Many(select = "com.itheima.dao.PermissionDao.findPermissionByRoleId"))
	})
	public List<Role> findRoleByUserId(String id) throws Exception;

	// @Select("select * from role")
	public List<Role> findAll() throws Exception;

	// @Insert("insert into role(roleName,roleDesc) values(#{roleName},#{roleDesc})")
	public void save(Role role) throws Exception;

	@Select("select * from role where id =#{roleId}")
	@Results({
			@Result(id = true, property = "id", column = "id"),
			@Result(property = "roleName", column = "role_name"),
			@Result(property = "roleDesc", column = "role_desc"),
			@Result(property = "permissions", column = "id", javaType = java.util.List.class,
					many = @Many(select = "com.itheima.dao.PermissionDao.findPermissionByRoleId"))
	})
	public Role findById(String roleId) throws Exception;

	/**
	 * 通过关联表查询role没有的权限
	 *
	 * @param roleId
	 * @return
	 */
	//@Select("SELECT * FROM permission WHERE id NOT IN(SELECT permissionId FROM role_permission WHERE roleId = #{roleId})")
	public List<Permission> findOtherPermission(String roleId);

	@Insert("insert into role_permission(roleId,permissionId) values(#{roleId},#{permissionId})")
	public void addPermissionToRole(@Param(value = "roleId") String roleId,@Param(value = "permissionId") String permissionId) throws Exception;
}
